<?php
namespace backend\models;

use Yii;
use yii\base\Model;
use yii\web\UploadedFile;
use common\models\Property;
use yii\web\BadRequestHttpException;

class UploadForm extends Model
{
    /**
     * @var UploadedFile
     */
    public $imageFile;

    /**
     * @var UploadedFile
     */
    public $imageFiles;

    /** 返回oss files */
    private $_files = [];

    /** 验证规则 */
    public function rules()
    {
        return [
            [['imageFile'], 'file', 'checkExtensionByMimeType' => true, 'extensions' => 'png, jpg'],
            [['imageFiles'], 'file', 'maxFiles' => 4, 'checkExtensionByMimeType' => true, 'extensions' => 'png, jpg'],
        ];
    }
    
    /**
     * 上传单张图片到oss.
     * @return string oss oss-request-url
     * @throws \yii\web\BadRequestHttpException
     */
    public function upload()
    {
        if ($this->imageFile = UploadedFile::getInstance(new Property(), 'thumbs')) {
            if ($this->validate()) {
                $path_name = 'lsol-house/property/' . date('Y-m-d', time()) . '/' . time() . '_' . mt_rand() . '.' . $this->imageFile->extension;
                $ossInfo = Yii::$app->oss->putObject($path_name, file_get_contents($this->imageFile->tempName));
                return $ossInfo['oss-request-url'];
            } else {
                throw new BadRequestHttpException($this->getFirstError('imageFile'));
            }
        }
    }

    /**
     * 批量上传图片到oss.
     * @return string _files
     * @throws \yii\web\BadRequestHttpException
     */
    public function uploads()
    {
        if ($this->imageFiles = UploadedFile::getInstancesByName('thumbs')) {
            if ($this->validate()) {
                foreach ($this->imageFiles as $file) {
                    $path_name = 'lsol-house/property/' . date('Y-m-d', time()) . '/' . time() . '_' . mt_rand() . '.' . $file->extension;
                    $ossInfo = Yii::$app->oss->putObject($path_name, file_get_contents($file->tempName));
                    $this->_files[] = $ossInfo['oss-request-url'];
                }
                return implode(',', $this->_files);
            } else {
                throw new BadRequestHttpException($this->getFirstError('imageFiles'));
            }
        }
    }
}
